/// CGFXShader.cpp
/// Matthew DiBernardo (Cryptex)
/// 07.28.09
///
/// See CGFXShader.h for usage information.

#include "CGFXShader.h"
#include <windows.h>

CGFXShader::~CGFXShader()
{
	cgDestroyEffect(m_effect);
}

bool CGFXShader::LoadEffect(CGcontext context, std::string fxName)
{
	m_effect = cgCreateEffectFromFile(context, fxName.c_str(), NULL);

	if(!m_effect)
	{
		//if(_DEBUG) // Enable Verbose Output in Debug Mode
		//	MessageBox(0, cgGetLastListing(context), "Unable to Load CgFX file.", MB_OK);
		return false;
	}

	// For the sake of simplicity, only one effect per file is
	// supported in Color Theory's engine.
	CGtechnique technique = cgGetFirstTechnique(m_effect);
	if(cgValidateTechnique(technique) == CG_FALSE)
	{
		//if(_DEBUG)
		//	MessageBox(0, cgGetTechniqueName(technique), L"Technique did not validate.", MB_OK);
		return false;
	}

	WorldViewProj = cgGetNamedEffectParameter(m_effect, "WorldViewProj");
	WorldViewIT = cgGetNamedEffectParameter(m_effect, "WorldViewIT");

	for(CGpass pass = cgGetFirstPass(technique); pass; pass = cgGetNextPass(pass))
	{
		m_pass.push_back(pass);
	}
	return true;
}

void CGFXShader::BindShader(void)
{
	BindPass(0);
}

void CGFXShader::UnbindShader(void)
{
	//cgSetPassState(NULL); // This might break! (If so, just comment it out)

	// If the above line does, in fact, break, this suggests that
	// the only way to unbind a CgFX shader is likely to disable
	// its profile. In this case, calling ShaderManager's
	// ReleaseAllShaders() function should be called after any
	// Cg Shader is done executing.
}

bool CGFXShader::BindPass(unsigned int _pass)
{
	if(_pass >= m_pass.size())
		return false;

	cgSetPassState(m_pass[_pass]);
	cgGLSetStateMatrixParameter(WorldViewProj, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);
	//cgGLSetStateMatrixParameter(WorldViewIT, CG_GL_MODELVIEW_MATRIX, CG_GL_MATRIX_INVERSE_TRANSPOSE);
	return true;
}